package com.test.mqtt.client;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessageCallback implements MqttCallback {
    private static final Logger log = LoggerFactory.getLogger(MessageCallback.class);

    @Autowired
    private EmqClient emqClient;

    // 丢失了服务端连接后触发的回调
    @Override
    public void connectionLost(Throwable throwable) {
        // 资源的清理，重连
        log.info("丢失了对服务端的连接");
        emqClient.reConnect();

    }
    // 应用收到消息后触发的回调
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        String message = new String(mqttMessage.getPayload());
        log.info("订阅者订阅到了消息，topic="+ s +",payload=" + message);
    }

    /**
     * 消息发布完成产生的回调
     *  QoS0：消息被网络发出后触发一次
     *  QoS1：当收到broker的PUBACK消息后触发
     *  QoS2：当收到broker的PUBCOMP消息后触发
     *
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        int messageId = iMqttDeliveryToken.getMessageId();  //消息id
    }
}
